# _*_ coding:utf-8 _*_
# @Time  : 2022.10.26
# @Author: zizlee
from fastapi import APIRouter, Query, Header
from hutool import security
from db import FAConnection
from v1_all_api.all_response import AllResponse

formula_api = APIRouter()


@formula_api.get('/my/')  # 搜索系统中自己创建的公式
def get_my_formula(ruizy_token: str = Header(...),
                   kw: str = Query(None), v: str = Query(None), page: int = Query(1), page_size: int = Query(30)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    user_id = person['uid']
    if security.operator_is_super_admin(person):
        user_id = '0'
    # 查询数据
    variety = v.upper() if v else '0'
    kw = kw.replace(' ', '%') if kw else '0'
    sql = """
        SELECT a.id,a.name,a.formula,a.frequency,a.unit  
        FROM datalib_sheet_column As a 
        INNER JOIN datalib_variety_sheet As b ON a.sheet_id=b.id 
        WHERE LENGTH(a.formula)>14 
          AND IF('0'=%s,TRUE,b.user_id=%s)
          AND IF('0'=%s,TRUE,a.name LIKE %s) 
          AND IF('0'=%s,TRUE,b.variety_en=%s);
    """
    prm = [user_id, user_id, kw, f'%{kw}%', variety, variety]
    db_conn = FAConnection()
    ret = db_conn.query_paginator(sql, param=prm, page=page, page_size=page_size)
    return AllResponse.operate_successfully(data=ret)
